
from PIL import Image
import os


def read_animated_gif(gif_path):
    """读取GIF文件的每一帧"""
    try:
        with Image.open(gif_path) as img:
            print(f"格式: {img.format}")
            print(f"尺寸: {img.size}")
            print(f"模式: {img.mode}")
            print(f"帧数: {getattr(img, 'n_frames', 1)}")

            frames = []
            # 如果是多帧图像，遍历所有帧
            if hasattr(img, 'n_frames') and img.n_frames > 1:
                for frame in range(img.n_frames):
                    img.seek(frame)
                    frames.append(img.copy())
                    print(f"帧 {frame}: 持续时间 {img.info.get('duration', 0)}ms")
            else:
                frames.append(img.copy())

            return frames
    except Exception as e:
        print(f"读取GIF文件出错: {e}")
        return []


def read_tiff_sequence(tiff_path):
    """读取多页TIFF文件的每一页"""
    try:
        with Image.open(tiff_path) as img:
            print(f"格式: {img.format}")
            print(f"尺寸: {img.size}")
            print(f"模式: {img.mode}")

            frames = []
            page = 0
            while True:
                try:
                    frames.append(img.copy())
                    print(f"页 {page}: 已读取")
                    page += 1
                    img.seek(page)
                except EOFError:
                    # 已到达文件末尾
                    break

            return frames
    except Exception as e:
        print(f"读取TIFF文件出错: {e}")
        return []


def save_frames(frames, output_dir, base_name):
    """将帧保存为单独的图像文件"""
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)

    for i, frame in enumerate(frames):
        output_path = os.path.join(output_dir, f"{base_name}_frame_{i:03d}.png")
        frame.save(output_path)
        print(f"已保存: {output_path}")


def display_image_info(image_path):
    """显示图像基本信息"""
    try:
        with Image.open(image_path) as img:
            print(f"文件: {image_path}")
            print(f"格式: {img.format}")
            print(f"尺寸: {img.size}")
            print(f"模式: {img.mode}")

            # 检查是否是序列图像
            if hasattr(img, 'n_frames'):
                print(f"总帧数: {img.n_frames}")

                # 显示每帧信息
                if img.n_frames > 1:
                    print("帧信息:")
                    for i in range(img.n_frames):
                        img.seek(i)
                        duration = img.info.get('duration', '未知')
                        print(f"  帧 {i}: 持续时间 {duration}ms")
            else:
                print("这是单帧图像")

    except Exception as e:
        print(f"读取图像信息出错: {e}")


if __name__=='__main__':
    # Image的4中基本属性
    ima = Image.open('birdnest.jpg')
    print(f'format: {ima.format}')
    print(f'mode: {ima.mode}')
    print(f'size: {ima.size} px')
    print(f'palette: {ima.palette}')

    # 读取GIF文件
    print("=== 读取GIF文件示例 ===")
    gif_frames = read_animated_gif("example.gif")
    if gif_frames:
        save_frames(gif_frames, "output_gif", "gif_frame")

    print("\n=== 显示图像信息示例 ===")
    # 显示图像基本信息
    display_image_info("example.gif")

